//登录页面
#include "loginwindow.h"
#include "ui_loginwindow.h"
#include"clientSock.h"
#include"erollwindow.h"
#include<iostream>
#include<string>
#include"recivedata.h"
#include<QMessageBox>
#include <QRegularExpressionValidator>
#include"MD5.h"
#include"mainwindow.h"

loginWindow::loginWindow(QWidget *parent, ThreadPool* pool)
    : QMainWindow(parent), ui(new Ui::loginWindow), thread(pool)
{
    ui->setupUi(this);

    QRegularExpressionValidator* validator = new QRegularExpressionValidator(
        QRegularExpression("^[0-9]+$"), this);
    ui->userName->setValidator(validator);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::LoginSignal,this,&loginWindow::plotDialogLogin,Qt::QueuedConnection);

}

loginWindow::~loginWindow()
{
    delete eWindow;
    delete ui;
}

//注册
void loginWindow::on_eroll_clicked()
{
    if (!eWindow) {
        eWindow = new erollWindow();
        // 当注册窗口销毁时，把指针置空即可
        connect(eWindow, &erollWindow::destroyed, this, [this]() {
            eWindow = nullptr;
        });
    }
    eWindow->show();
}

// 在 loginWindow.cpp 中实现
void loginWindow::closeEvent(QCloseEvent *event)
{
    ReceiveData::getInstance().stopFlag = true;

    if (thread) {
        thread->stopPool();
        delete thread;
        thread = nullptr;
    }

    // 可以添加其他资源释放的代码
    if(eWindow){
        delete eWindow;
        eWindow = nullptr;
    }
    delete ui;
    event->accept();
}

void loginWindow::on_pushButton_2_clicked()
{
//    Client::getInstance().connectSever();
    std::string phone = ui->userName->text().toStdString();
    QString password = ui->userPassword->text();
    if(phone.empty()|password.isEmpty()){
        QMessageBox::information(this,"登录","账号密码不全");
        return;
    }
    std::string pass = md5Encrypt(password).toStdString();
    //头
    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::LOGIN;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.timestamp = CloudDrive::now_millis();
    // 文件信息
    CloudDrive::UserInfo uIfo;
    strncpy(uIfo.account,phone.c_str(),CloudDrive::MAX_ACCOUNT_LEN - 1);
    strncpy(uIfo.password,pass.c_str(),CloudDrive::MAX_ACCOUNT_LEN - 1);

    Client::getInstance().sendData(CloudDrive::makeUserPacket(pkt,uIfo,0));

}

void loginWindow::plotDialogLogin(CloudDrive::MessageReturn msg)
{
    switch (msg) {
    case CloudDrive::MessageReturn::LOGIN_OK:{
        this->hide();
        mainWindow::getInstance().show();
        mainWindow::getInstance().init(ui->userName->text().toStdString());
        break;
    }
    case CloudDrive::MessageReturn::LOGIN_NOTEXIST:{
        QMessageBox::information(this,"登录","账号或密码错误");
        break;
    }
    case CloudDrive::MessageReturn::LOGIN_NO:{
        QMessageBox::information(this,"登录","登录失败");
        break;
    }
    default:
        break;
    }
}

std::string loginWindow::getUserName()
{
    return ui->userName->text().toStdString();
}
